const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const multipart = require('connect-multiparty');
var cookie = require('cookie-parser');
// function
const login = require('./routes/login');
const register = require('./routes/register');
const quit = require('./routes/quit');
const getCompanies = require('./routes/getCompanies');
const addCompany = require('./routes/addCompany');
const addJob = require('./routes/addJob');
const getJobs = require('./routes/getJobs');
const setCookie = require('./routes/setCookie');
const setComments = require('./routes/setComments');
const getComments = require('./routes/getComments');

app.use(bodyParser.json()); //数据JSON类型
app.use(bodyParser.urlencoded({
  extended: false
})); //解析post请求数据
app.use(cookie());

//设置跨域访问
app.all('*', function (req, res, next) {
  // res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Content-Type", "application/form-data;charset=utf-8");
  res.header("Access-Control-Allow-Credentials", true);

  // console.log(req.url);

  if (!req.cookies.username && req.url !== '/list?' && req.url !== '/quit?' && req.url !== '/login' && req.url !== '/register') {
    // 若当前没有 cookie 值, 且请求不为登录或注册请求, 则重定向
    return res.json({
      status: 3,
      data: {
        url: "http://127.0.0.1:8080/#/login"
      }
    })
  } else {
    setCookie(req, res);
  }
  next();
});

var multipartMiddleware = multipart();

app.post('/login', multipartMiddleware, function (req, res) {
  const data = req.body;
  const {
    username,
    pass
  } = data;
  login(username, pass, res);
});

app.post('/register', multipartMiddleware, function (req, res) {
  const data = req.body;
  register(data, res);
});

app.get('/quit', multipartMiddleware, function (req, res) {
  quit(req, res);
})

app.get('/list', multipartMiddleware, function (req, res) {
  const data = req.body;
  getCompanies(data, res);
});

app.post('/publish', multipartMiddleware, function (req, res) {
  const data = req.body;
  addJob(data, res);
  addCompany(data, req, res);
});

app.get('/company=:company', multipartMiddleware, function (req, res) {
  const data = req.body;
  data._id = req.params.company;
  getJobs(data, res);
})

app.post('/setComments', multipartMiddleware, function (req, res) {
  const data = req.body;
  setComments(data, req, res);
})

app.get('/getComments', multipartMiddleware, function (req, res) {
  const data = req.body;
  data.name = req.cookies.username;
  getComments(data, req, res);
})

app.listen(3000);
console.log('Listening on port 3000...');
